package com.hxgis.oc.cma;

import cn.hutool.json.JSONObject;
import com.hxgis.oc.cma.util.CmaFileInfo;
import com.hxgis.oc.cma.util.CmaFileRequest;
import com.hxgis.oc.cma.util.CmaRequest;
import com.hxgis.oc.config.OConfig;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RadarRequest extends CmaFileRequest {
    public static final String dataCode = "RADA_L2_FMT";
    private static final String interfaceId = "getRadaFileByTimeRangeAndStaId";
    private String station;
    public RadarRequest(String name){
        station = name;
    }

    @Override
    public String getDataTable() {
        return station;
    }

    @Override
    public LocalDateTime parseTimeFromName(String fileName)
    {
        LocalDateTime localDateTime = null;
        String[] list = fileName.split("_");
        if(list.length > 4){
            String timeYYYYMMDDHHMMSS = list[4];
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            try{
                localDateTime = LocalDateTime.parse(timeYYYYMMDDHHMMSS,formatter);
            }catch (Exception ignored){}
        }

        return localDateTime;
    }

    @Override
    public List<CmaFileInfo> query(LocalDateTime fromTime, LocalDateTime toTime) {
        return query(station,fromTime,toTime);
    }

    public List<CmaFileInfo> query(String station, LocalDateTime fromTime, LocalDateTime toTime)
    {
        LocalDateTime utc_st = fromTime;
        LocalDateTime utc_ed = toTime;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String fromTimeStr = formatter.format(utc_st);
        String toTimeStr = formatter.format(utc_ed);

        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("dataCode",dataCode);
        requestParams.put("staIds",station);
        requestParams.put("timeRange", "[" + fromTimeStr + "," + toTimeStr + ")");
        List<JSONObject> list = CmaRequest.queryJsonData(requestParams,interfaceId);
        return toFileInfoList(list,name -> generateTimeStamp(name));
    }
}
